package com.shou.controller;

import com.shou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
//
@Controller
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/registration")
    public String showRegistrationPage() {
        return "register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String registerUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("confirmPassword") String confirmPassword,
            Model model
    ) {
        try {
            // Validate if passwords match
            if (!password.equals(confirmPassword)) {
                model.addAttribute("errorMessage", "Passwords do not match.");
                return "register";
            }

            // Call the userService to handle user registration
            boolean registrationResult = userService.registerUser(username, password);

            if (registrationResult) {
                // Registration successful, redirect to login page or another success page
                return "redirect:/index";
            } else {
                model.addAttribute("errorMessage", "Registration failed. Please try again.");
                return "register";
            }
        } catch (Exception e) {
            // Handle exceptions appropriately
            e.printStackTrace();
            model.addAttribute("errorMessage", "An error occurred during registration.");
            return "register";
        }
    }
}
